package com.cube.share.thread.controller;

import com.cube.share.base.templates.ApiResult;
import com.cube.share.thread.config.CurrentUser;
import com.cube.share.thread.entity.SysUser;
import com.cube.share.thread.service.AsyncService;
import com.cube.share.thread.service.JustService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author poker.li
 * @date 2021/7/22 0:35
 */
@RestController
@Slf4j
public class JustController {

    private static final int COUNT = 10;

    @Resource
    ThreadPoolExecutor customExecutor;

    @Resource
    JustService justService;

    @Resource
    private AsyncService asyncService;

    @GetMapping("/action")
    public void action() throws Exception {
        asyncService.doAction();
    }

    @GetMapping("/user")
    public ApiResult<Void> request() {
        //模拟获取用户信息,这一步一般在拦截器中进行
        SysUser sysUser = new SysUser();
        sysUser.setId(11235813L);
        sysUser.setName("wang");
        //在当前线程中设置用户信息
        CurrentUser.setUser(sysUser);
        CurrentUser.setUserId(sysUser.getId());
        justService.doAction();

        //新线程中获取用户信息
        customExecutor.submit(() -> {
            try {
                justService.doAction();
                //InheritableThreadLocal
                System.out.println("可在父子线程之间传递的用户信息:" + CurrentUser.inheritableUser());
            } finally {
                CurrentUser.removeAll();
            }
        });
        return ApiResult.success();
    }

}
